package demo1;

public class TestHeap {
    public int [] elem;
    public int usedSize;
    public TestHeap(){
        int[] elem = new int[10];
    }

    //创建一个大根堆
    public void createHeap(int [] array){
        for(int i = 0; i < array.length;i++){
            elem[i] = array[i];
            usedSize++;
        }

        for(int parent = (usedSize -1 -1)/2;parent >=0;parent--){
            shiftDown(parent,usedSize);
        }
    }

    /**
     *
     * @param parent 每颗子树的根节点
     * @param len  每颗子树的结束位置
     */

    public  void shiftDown(int parent,int len){
        int child = 2*parent+1;
        while(child < len){
            //小心越界
            if(child +1 < len && elem[child] < elem[child +1]){
                child = child + 1;
            }
            if(elem[child] > elem[parent]){
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                parent = child;
                child = 2*parent+1;
            }
        }

    }
}
